﻿using System;
using System.IO;
using System.Threading;

namespace Check
{
    /// <summary>
    /// 一个默认使用文件进行记录的日志器。
    /// </summary>
    public class FileLogger
    {
        public static void LogInfo(string message)
        {
            string msg = string.Format(@"{0}|{1}|Inform|{2}" + Environment.NewLine, DateTime.Now, Thread.CurrentThread.ManagedThreadId, message);
            AppendAllText(msg);
        }
        public static void LogWarn(string message)
        {
            string msg = string.Format(@"{0}|{1}|Warn|{2}" + Environment.NewLine, DateTime.Now, Thread.CurrentThread.ManagedThreadId, message);
            AppendAllText(msg, LogType.Warn);
        }
        public static void LogDebug(string message)
        {
            string msg = string.Format(@"{0}|{1}|Debug|{2}" + Environment.NewLine, DateTime.Now, Thread.CurrentThread.ManagedThreadId, message);
            AppendAllText(msg, LogType.Debug);
        }
        public static void LogError(string title, Exception e)
        {
            var stackTrace = e.StackTrace;//需要记录完整的堆栈信息。
            e = e.GetBaseException();

            string msg = string.Format(@"{0}|{1}|Error|{2}" + Environment.NewLine, DateTime.Now, Thread.CurrentThread.ManagedThreadId, title + e.ToString());
            AppendAllText(msg, LogType.Error);
        }
        private static void AppendAllText(string contents, LogType logType = LogType.Info)
        {
            string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string logfile = path + "/" + logType + DateTime.Now.ToString("yyyyMMdd") + ".log";
            if (!Directory.Exists(path)){
                Directory.CreateDirectory(path);
            }
            File.AppendAllText(logfile, contents);
        }
    }
    public enum LogType
    {
        Info,
        Warn,
        Debug,
        Error,
        Trace
    }
}